package com.zerox.sbdemo.controller;

import com.zerox.sbdemo.Person;
import com.zerox.sbdemo.pojo.Fruit;
import com.zerox.sbdemo.service.FruitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Controller
public class HelloController {

    @Autowired
    private FruitService fruitService;

//    @Value("${person.name}")
//    private String name;
//
//    @Value("${person.birthday}")
//    private String birthday;
    @Autowired
    private Person person;

    @GetMapping("/hello")
    @ResponseBody
    public String Hello(){
//        return "hello "+person.getName();
        return "hello "+person.getName()+",我的爱好："+ Arrays.toString(person.getHobby().toArray())+",出生日期："+new SimpleDateFormat("yyyy-HH-3").format(person.getBirthday());
    }

    @GetMapping("list")
    public String list(Model model){
        List<Fruit> list = fruitService.list();
        model.addAttribute("list",list);
        return "list";
    }
//    @GetMapping("/view")
//    public String view(Model model,Integer id){
//        fruitService.selectById(id);
//        model.addAttribute();
//        return "view";
//    }

        @GetMapping("/user/{id}")
    public String view(Model model,@PathVariable("id")Integer id){
        Fruit Fruit= fruitService.select(id);
        model.addAttribute("Fruit",Fruit);
        return "view";
    }

    @GetMapping("toAdd")
    public String toAdd(){
        return "add";
    }


    @PostMapping("/user")
    public String add(Fruit fruit)
    {
        int add = fruitService.add(fruit);
        if (add>0){
            return "redirect:list";
        }
        return null;
    }
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id")Integer id, HttpServletRequest request){
        int delete = fruitService.delete(id);

        return "redirect:/list";
    }

    @GetMapping("/update/{id}")
    public String toUpdate(Model model,@PathVariable("id")Integer id){
        Fruit fruit= fruitService.select(id);
        model.addAttribute("fruit",fruit);
        return "update";
    }
    @PostMapping("/update")
    public String toUpdate(Fruit fruit)
    {
        int update = fruitService.update(fruit);
        if (update>0){
            return "redirect:list";
        }
        return null;
    }
}
